<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数:{{ total }}条</span>
        </template>
        <template #right>
          <el-button
            v-allow="'import_excel'"
            type="warning"
            size="small"
            @click="$router.push('/import')"
          >excel导入</el-button>
          <el-button

            v-allow="'export_excel'"
            type="danger"
            size="small"
            @click="exportExcel"
          >excel导出</el-button>
          <el-button
            v-allow="'add'"
            type="primary"
            size="small"
            @click="hAdd"
          >新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table
          :default-sort="{prop: 'date', order: 'descending'}"
          :data="list"
          border
        >
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />

          <el-table-column label="员工头像" width="100">
            <template #default="{row}">
              <el-row type="flex" justify="center">
                <img
                  :src="row.staffPhoto"
                  alt=""
                  style="width:100%"
                  @click="showImg(row.staffPhoto)"
                >

              </el-row></template>

          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template #default="{row}">
              {{ formatEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="assignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="del(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 5, 10, 15]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog title="新增" :visible.sync="showDialog">
        <empDialog v-if="showDialog" @close="close" @success="hSuccess" />
      </el-dialog>
      <el-dialog title="生成二维码" :visible.sync="showImgDialog">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <!-- 分配角色 -->
      <el-dialog
        v-if="showRole"
        title="分配角色"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showRole"
      >
        <assign-role :cur-id="curId" @success="showRole=false" @close="showRole=false" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import assignRole from '../employees/assignRole.vue'

import QRcode from 'qrcode'
import empDialog from '@/views/employees/empDialog.vue'
import EmployeeEnum from '@/constant/employees'
import { getEmployeeList } from '@/api/employees'
import { delEmployeeList } from '@/api/employees'
import { transExportExcel } from '@/utils'
const hireType = {}
EmployeeEnum.hireType.forEach(item => {
  hireType[item.id] = item.value // {1:正式，2：非正式}
})
export default {

  components: {
    empDialog, assignRole
  },
  data() {
    return {
      curId: '',
      showRole: false,
      list: [],
      page: 1,
      size: 5,
      total: 0,
      showDialog: false,
      showImgDialog: false

    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {

    assignRole(id) {
      this.showRole = true
      this.curId = id
    },
    showImg(url) {
      if (url) {
        this.showImgDialog = true
        this.$nextTick(() => {
          const canvas = this.$refs.myCanvas
          QRcode.toCanvas(canvas, url)
        })
      } else {
        this.$message.error('请输入正确的数据')
      }
    },
    exportExcel() {
      import('@/vendor/Export2Excel').then(excel => {
        // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
        // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        // const list = this.list
        // const data = this.formatJson(filterVal, list)
        const { header, data } = transExportExcel(this.list)
        console.log(header, data)
        excel.export_json_to_excel({
          header,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
      })
    },
    async del(id) {
      try {
        const res = await delEmployeeList(id)
        console.log('delEmployeeList', res)

        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        this.$message.success(res.message)
        this.loadEmployeeList()

        // 保存数据
      } catch (err) {
        console.log('delEmployeeList', err)
      }
    },
    hSuccess() {
      this.total++
      const pageMax = Math.ceil(this.total / this.size)
      this.page = pageMax
      this.loadEmployeeList()
      this.showDialog = false
    },
    close() {
      this.showDialog = false
    },
    hAdd() {
      this.showDialog = true
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.size = val
      this.loadEmployeeList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployeeList()
    },
    formatEmployment(id) {
      return hireType[id] || '未知'
    },
    async loadEmployeeList() {
      const res = await getEmployeeList({ page: this.page, size: this.size })
      console.log(res, 'getEmployeeList')
      this.list = res.data.rows
      this.total = res.data.total
    }
  }
}
</script>
